#include "StdAfx.h"
#include "ObserverHelper.h"

namespace UTIL {

ObserverHelper::ObserverHelper(LPCTSTR pszObserverClassFilter, UINT nEvent, WPARAM wParam, LPARAM lParam)
	: m_pszObserverClassFilter(pszObserverClassFilter)
	, m_nEvent(nEvent)
	, m_wParam(wParam)
	, m_lParam(lParam)
{
	m_nObserverClassPrefixLength = _tcslen(m_pszObserverClassFilter);
}

void ObserverHelper::Notify(HWND hwnd)
{
	TCHAR szClassName[64];
	::GetClassName(hwnd, szClassName, sizeof(szClassName)/sizeof(TCHAR));

	if ( _tcsncmp(szClassName, m_pszObserverClassFilter, m_nObserverClassPrefixLength) )
		return;

	ATLTRACE( _T("Posting to 0x%x\n"), hwnd );
	::PostMessage(hwnd, m_nEvent, m_wParam, m_lParam);
}

void ObserverHelper::NotifyObservers(LPCTSTR pszObserverClassFilter, UINT nEvent, WPARAM wParam/* = 0*/, LPARAM lParam/* = 0*/)
{
	ObserverHelper helper(pszObserverClassFilter, nEvent, wParam, lParam);

	EnumWindows(NotifyAllWindowsProc, (LPARAM)&helper);
}

BOOL CALLBACK ObserverHelper::NotifyAllWindowsProc(HWND hwnd, LPARAM lParam)
{
	ATLASSERT(lParam);
	((ObserverHelper*)lParam)->Notify(hwnd);

	::EnumChildWindows(hwnd, NotifyChildWindowsProc, lParam);

	return TRUE;
}

BOOL CALLBACK ObserverHelper::NotifyChildWindowsProc(HWND hwnd, LPARAM lParam)
{
	ATLASSERT(lParam);
	((ObserverHelper*)lParam)->Notify(hwnd);

	return TRUE;
}

}; //namespace UTIL
